/*
 * @Date: 2024-04-01 09:33:36
 * @LastEditors: bingkui.wu 
 * @LastEditTime: 2024-04-03 20:18:12
 * @Description: 缓存处理
 */
// @ts-nocheck
import storage from '@system.storage';
import utils from '../helper/utils';


const TOKEN_KEY = "token";
const USERINFO_KEY = "user_info";
const USER_BOOK_SELECT = "user_book_select";

/**
 * 获取本地缓存
 * @param {string} key 健名
 * @returns 
 */
const getStorage = async (key) => {
    if (utils.isBrowser()) {
        return localStorage.getItem(key);
    }
    return new Promise((resolve, reject) => {
        storage.get({
            key,
            success: resolve,
            fail: reject
        });
    });
}

/**
 * 设置本地缓存
 * @param {string} key 健名
 * @param {object} value 健值
 * @returns 
 */
const setStorage = async (key, value) => {
    if (utils.isBrowser()) {
        return localStorage.setItem(key, value);
    }
    return new Promise((resolve, reject) => {
        return storage.set({
            key,
            value,
            success: resolve,
            fail: reject
        });
    });
}

/**
 * 删除本地缓存
 * @param {string} key 健名
 * @returns 
 */
const removeStorage = async (key) => {
    if (utils.isBrowser()) {
        return localStorage.removeItem(key);
    }
    return new Promise((resolve, reject) => {
        return storage.delete({
            key,
            success: resolve,
            fail: reject
        });
    });
}

/**
 * 获取缓存token
 * @returns 
 */
export const getToken = () => {
    return getStorage(TOKEN_KEY);
}

/**
 * 设置token到缓存
 * @param {string} token 
 * @returns 
 */
export const setToken = (token) => {
    return setStorage(TOKEN_KEY, token);
}

/**
 * 删除token缓存
 */
export const removeToekn = () => {
    return removeStorage(TOKEN_KEY);
}

/**
 * 获取缓存用户信息
 * @returns 
 */
export const getUserStroageInfo = async () => {
    const value = await getStorage(USERINFO_KEY);
    if(!value){
        return null;
    }
    return JSON.parse(value);
}

/**
 * 设置用户信息到缓存
 * @param {object} info 
 * @returns 
 */
export const setUserStroageInfo = (info) => {
    return setStorage(USERINFO_KEY, JSON.stringify(info));
}

/**
 * 删除用户信息缓存
 */
export const removeUserStorageInfo = () => {
    return removeStorage(USERINFO_KEY);
}

/**
 * 保存用户选择的教材
 * @param {number} categoryId 教材Id
 * @param {number} gradeId 年级Id
 */
export const setSelectedBookStorage = async (categoryId, gradeId) => {
    return setStorage(USER_BOOK_SELECT, JSON.stringify({categoryId, gradeId}))
}

/**
 * 获取用户选择的教材配置信息
 */
export const getSelectedBookStroage = async () => {
    const value = await getStorage(USER_BOOK_SELECT);
    if(value) {
        return JSON.parse(value);
    }else{
        return null;
    }
}